﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data;
using System.Data.Linq;
using System.IO;

namespace FusionDotNet
{
    /// <summary>
    /// Inserts rows in a Google Fusion table.
    /// </summary>
    public class InsertCommand : PostCommand<SelectResult>
    {
        private DataTable m_RowData;

        /// <summary>
        /// Constructs a InsertCommand.
        /// </summary>
        /// <param name="rowData">DataTable containing the rows to insert.</param>
        public InsertCommand(System.Data.DataTable rowData)
        {
            BuildUpdateCommand(rowData);
        }

        private void BuildUpdateCommand(System.Data.DataTable rowData)
        {
            m_RowData = rowData;

            string insertStatement = "sql=" + CreateInsertFromDataTable(rowData);

            Encoding encoding = GetContentEncoding();
            PostContent = encoding.GetBytes(insertStatement.ToString());
        }

        private static string CreateInsertFromDataTable(System.Data.DataTable rowData)
        {
            List<string> columnHeaders = new List<string>();
            foreach (DataColumn column in rowData.Columns)
            {
                columnHeaders.Add(column.ColumnName);
            }
            string headerTemplate = String.Join(",", columnHeaders.Select(i => string.Format("'{0}'", i)).ToArray());

            StringBuilder builder = new StringBuilder();
            foreach (DataRow row in rowData.Rows)
            {
                string[] rowValues = row.ItemArray.Select(i => String.Format("'{0}'", i)).ToArray();
                builder.AppendFormat("INSERT INTO {0} ({1}) VALUES ({2});", rowData.TableName, headerTemplate, String.Join(",", rowValues));
            }
            return builder.ToString();
        }

        internal override SelectResult CreateResult(StreamReader reader)
        {
            string columnHeader = reader.ReadLine();
            if (!m_RowData.Columns.Contains(columnHeader))
            {
                m_RowData.Columns.Add(columnHeader);
            }

            int rowIndex = 0;
            while (!reader.EndOfStream)
            {
                m_RowData.Rows[rowIndex][columnHeader] = reader.ReadLine();
                rowIndex++;
            }

            SelectResult result = new SelectResult(m_RowData);
            return result;
        }

    }
}
